package cn.jhc.factory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectionFactory {
	
	private static final String PREFIX = "jdbc:mysql://localhost/books?";
	
	private static Properties dbProperties = new Properties();
	
	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		InputStream input = ConnectionFactory.class.getResourceAsStream("/db.properties");
		
		try {
			dbProperties.load(input);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		
	}
	
	public static Connection getConnection()  {
		Connection connection = null;
		try {
			String url = PREFIX + "user=" + dbProperties.getProperty("username") + 
					"&password=" + dbProperties.getProperty("password");
			connection = DriverManager.getConnection(url);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return connection;
	}

}
